package com.jkb.trainjieba;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;

import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

/**
 * 
 * @author wangbin
 * 功能：算出词在不同类别下的tfidf。词频(词在此类别下的数量/该类别的总词数量)
 *     对SplitWordsMR产生的数据进行处理，总词量使用TypesWithWordsTotalNumber产生的数据,使用IDF数据。
 * 输入：词\t\t\t文章类别\t\t\turl
 * 输出：词\t文章类别\tfidf
 * 运行步骤：第四步
 * 
 */
public class ObtainTFIDF {

	public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
		//args0:dst
		//args1:out
		//args2:splitMB
		//args3:reduce num
		//args4:hdfs file每个类别下的总词数
		//args5:hdfs IDF file
		if(args.length != 6){
			System.out.println("args0:dst");
			System.out.println("args1:out");
			System.out.println("args2:splitMB");
			System.out.println("args3:reduce num");
			System.out.println("hdfs file每个类别下的总词数");
			System.out.println("hdfs IDF file");
			System.exit(0);
		}
		int SplitMB = Integer.valueOf(args[2]);
		String dst = args[0];
		String out = args[1];
		Configuration conf = new Configuration();
		conf.set("mapreduce.input.fileinputformat.split.maxsize", String.valueOf(SplitMB * 1024 * 1024));
		conf.set("mapred.min.split.size", String.valueOf(SplitMB * 1024 * 1024));
		conf.set("mapreduce.input.fileinputformat.split.minsize.per.node", String.valueOf(SplitMB * 1024 * 1024));
		conf.set("mapreduce.input.fileinputformat.split.minsize.per.rack", String.valueOf(SplitMB * 1024 * 1024));
		Job job = Job.getInstance(conf);
		FileInputFormat.addInputPath(job, new Path(dst));
		FileOutputFormat.setOutputPath(job, new Path(out));
		
		job.addCacheFile(new Path(args[4]).toUri());
	    job.addCacheFile(new Path(args[5]).toUri());
		job.setMapperClass(TFMap.class);
		job.setReducerClass(TFReduce.class);
		
		job.setNumReduceTasks(Integer.valueOf(args[3]));
		
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(LongWritable.class);
		
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(DoubleWritable.class);
		
		job.setJarByClass(ObtainTFIDF.class);
        job.waitForCompletion(true);

	}
	
	public static class TFMap extends Mapper<Object,Text,Text,LongWritable>{
		
		public final static String SP = "\t\t\t";
		
		public final static String SP2 = "\t";
		
		@Override
		public void map(Object key,Text value,Context context) throws IOException, InterruptedException{
			String[] line = value.toString().split(SP);
			if(line.length >= 3){
				String word = line[0];
				String type = line[1];
				context.write(new Text(word + SP2 + type),new LongWritable(1));
			}
		}
	}
	
	public static class TFReduce extends Reducer<Text,LongWritable,Text,DoubleWritable>{
		
		public final static String SP = "\t";
		
		//类别  - 总词数量
		HashMap<String,Long> cache = new HashMap<String,Long>();
		
		//词  - idf
		HashMap<String,Double> idf_cache = new HashMap<String,Double>();
		
		@Override
		public void setup(Context context) throws IOException {
			
			//Path[] paths = context.getLocalCacheFiles();
			URI[] paths = context.getCacheFiles();
			BufferedReader reader = new BufferedReader(new FileReader(paths[0].toString()));
			String line;
			while((line = reader.readLine()) != null){
				String[] data = line.split(SP);
				cache.put(data[0], Long.parseLong(data[1]));				
			}
			BufferedReader idf_reader = new BufferedReader(new FileReader(paths[1].toString()));
			String idf_line;
			//加载idf值
			while((idf_line = idf_reader.readLine()) != null){
				String[] idf = idf_line.split(SP);
				idf_cache.put(idf[0], Double.valueOf(idf[1]));
			}
		}
		
		@Override
		public void reduce(Text key,Iterable<LongWritable> values,Context context) throws IOException, InterruptedException {
			long sum = 0;//某类别下某词出现次数
			for(LongWritable v : values){	
				sum += v.get();
			}
			String word = key.toString().split(SP)[0];
			String type = key.toString().split(SP)[1];
			double tf = (double)sum/cache.get(type).longValue();
			double tfidf = tf*(idf_cache.get(word).doubleValue());
			context.write(key,new DoubleWritable(tfidf));//词在某个类别下对应的tfidf值
		}		
	}

}
